/** @file    FormSessionManager.cpp
 *  @author  Alessandro Polo
 *  @version $Id: FormSessionManager.cpp 2867 2010-08-07 20:44:51Z alex $
 *  @brief
 * File containing methods for the wosh::gui::FormSessionManager class.
 * The header for this class can be found in FormSessionManager.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include "FormSessionManager.h"
 #include "ui_FormSessionManager.h"
 #include <core/SessionManager.h>
 #include <core/List.h>

 #include <QtGui/QInputDialog>
 #include <QtGui/QMessageBox>


using namespace std;
namespace wosh {
 namespace gui {

 WOSH_REGISTER(wosh::gui::FormSessionManager, "wosh::gui::IWidgetGeneric", 1.0, _static_FormSessionManager )
 WOSH_GUI_MAP(wosh::gui::FormSessionManager, "wosh::SessionManager", 0.0, _static_Map_FormSessionManager )

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

FormSessionManager::FormSessionManager(QWidget *parent)
	: IWidgetGeneric(parent) {
	this->m_ui = new Ui::FormSessionManager();
	this->m_ui->setupUi(this);

	IWidgetGeneric::setTargetURI(_SessionManager_URI);
	buildMenus();

	// tab Busses [0]
	this->m_ui->tableView->setResizeStretch(1);
	this->m_ui->tableView->getTableView()->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this->m_ui->tableView, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );
	connect(this->m_ui->tableView, SIGNAL(tableContextMenuRequested(const QPoint&, const QModelIndex&)),this, SLOT(tableView_ContextMenu(const QPoint&, const QModelIndex&)) );
	connect(this->m_ui->btnMonitorBus, SIGNAL(clicked()), this, SLOT(btnMonitorBus_clicked()));
	connect(this->m_ui->btnCreateBus, SIGNAL(clicked()), this, SLOT(btnCreateBus_clicked()));
	connect(this->m_ui->btnStartBus, SIGNAL(clicked()), this, SLOT(btnStartBus_clicked()));
	connect(this->m_ui->btnStopBus, SIGNAL(clicked()), this, SLOT(btnStopBus_clicked()));
	connect(this->m_ui->btnFlushQueue, SIGNAL(clicked()), this, SLOT(btnFlushQueue_clicked()));
}

FormSessionManager::~FormSessionManager() {
	delete this->m_ui;
 }

void FormSessionManager::changeEvent(QEvent *e) {
	QWidget::changeEvent(e);
	if ( e->type() == QEvent::LanguageChange )
		this->m_ui->retranslateUi(this);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormSessionManager::refreshAll() {
	this->setWindowTitle( QString("Session Manager [%1]").arg(this->getTargetURI().getKernelName().c_str()) );
	this->m_ui->tableView->refreshData();
 }

void FormSessionManager::btnMonitorBus_clicked() {
	QMessageBox::critical(this, tr("NOT Implemented!"), tr("FormSessionManager::btnMonitorBus_clicked()") );
 }

void FormSessionManager::btnCreateBus_clicked() {
//	bool ok;
//	QString busname = QInputDialog::getText(this, tr("Create New Bus.."), tr("Bus Name:"), QLineEdit::Normal, "wosh.Bus.", &ok);
//	if ( !ok || busname.isEmpty() )
//		return;
//	QString bustype = QInputDialog::getText(this, tr("Select Type for Bus %1..").arg(busname), tr("Bus Type (including namespace, case sensitive):"), QLineEdit::Normal, "wosh::BusRing", &ok);
//	List* args = List::createFrom<Variant>(busname.toLatin1().data(), bustype.toLatin1().data());
//	executeRemoteMethod( _SessionManager_METHOD_create_bus, args );
 }

void FormSessionManager::btnStartBus_clicked() {
	Variant busName = this->m_ui->tableView->getCurrentItemAsVariantAtCol(1);
	controlBus(busName, (int)Bus::STATE_STARTED);
 }

void FormSessionManager::btnStopBus_clicked() {
	Variant busName = this->m_ui->tableView->getCurrentItemAsVariantAtCol(1);
	controlBus(busName, (int)Bus::STATE_STOPPED);
 }

void FormSessionManager::btnFlushQueue_clicked() {
	Variant busName = this->m_ui->tableView->getCurrentItemAsVariantAtCol(1);
	controlBus(busName, "flush");
 }

void FormSessionManager::controlBus( const Variant& busname, const Variant& action ) {
	List* args = new List(2);
	args->push_back( busname.clone() );
	args->push_back( action.clone() );
//	executeRemoteMethod( _SessionManager_METHOD_control_bus, args );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormSessionManager::buildMenus() {
	this->menuTitle = new QAction(this);
	this->menuTitle->setEnabled(false);

	this->menuSharedLocal = new QAction(this);
	this->menuSharedLocal->setText(tr("&Locally Shared"));
	this->menuSharedLocal->setCheckable(true);
	this->menuSharedNetwork = new QAction(this);
	this->menuSharedNetwork->setText(tr("&Network Shared"));
	this->menuSharedNetwork->setCheckable(true);
	this->menuFlush = new QAction(this);
	this->menuFlush->setText(tr("&Flush queue"));
	this->menuSendMessage = new QAction(this);
	this->menuSendMessage->setText(tr("&Send Message.."));

	this->menuTable = new QMenu(this);
	this->menuTable->addAction(this->menuTitle);
	this->menuTable->addSeparator();
	this->menuTable->addAction(this->menuSharedLocal);
	this->menuTable->addAction(this->menuSharedNetwork);
	this->menuTable->addSeparator();
	this->menuTable->addAction(this->menuFlush);
	this->menuTable->addSeparator();
	this->menuTable->addAction(this->menuSendMessage);

 }

void FormSessionManager::tableView_ContextMenu( const QPoint& pos, const QModelIndex& index ) {
	QPoint globalPos = this->mapToGlobal(pos);
	if ( !index.isValid() || index.row() == 0 ) return;
	Variant busName = this->m_ui->tableView->getCurrentItemAsVariantAtCol(1);
	Variant busType = this->m_ui->tableView->getCurrentItemAsVariantAtCol(2);
	Variant locshared = this->m_ui->tableView->getCurrentItemAsVariantAtCol(4);
	Variant netshared = this->m_ui->tableView->getCurrentItemAsVariantAtCol(5);

	this->menuTitle->setText( busName.toString().c_str() );
	this->menuTitle->setIcon( GuiUtilities::createIconFor(busType.toString()) );
	this->menuSharedLocal->setChecked( locshared.toBoolean(false) );
	this->menuSharedNetwork->setChecked( netshared.toBoolean(false) );

	QAction* selected = this->menuTable->exec( globalPos );
	if ( selected == this->menuSharedLocal ) {
		if ( this->menuSharedLocal->isChecked() )
			controlBus(busName, "+local");
		else
			controlBus(busName, "-local");
	 }
	else if ( selected == this->menuSharedNetwork ) {
		if ( this->menuSharedNetwork->isChecked() )
			controlBus(busName, "+network");
		else
			controlBus(busName, "-network");
	 }
	else if ( selected == this->menuFlush )
		controlBus(busName, "flush");
	else if ( selected == this->menuSendMessage ) {


	 }
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormSessionManager::busMessage( const Message& message, const Bus* ) {
	if ( message.isEmpty() || !message.getContent()->isResponse() ) return;
	if ( !isMessageForMeOrFromTarget(message) ) return;
	const wosh::Response* response = message.getContent()->asResponse();

	this->m_ui->tableView->evalResponse(response);

/*	if ( response->getMethod() == _SessionManager_METHOD_create_bus ) {
		if ( WFAILED(response->getReturnValue()) )
			QMessageBox::warning(this, this->windowTitle(), tr("FAILED#%1 Creating Bus!").arg(response->getReturnValue()) );
		else
			QMessageBox::information(this, this->windowTitle(), tr("Bus has been created!") );
		refreshAll();
	 }
	else if ( response->getMethod() == _SessionManager_METHOD_control_bus ) {
		if ( WFAILED(response->getReturnValue()) )
			QMessageBox::warning(this, this->windowTitle(), tr("FAILED#%1 Applying changes to Bus!").arg(response->getReturnValue()) );
		else
			QMessageBox::information(this, this->windowTitle(), tr("Bus has been updated!") );
		refreshAll();
	 }
	else
	*/
		promptMethodResponse(message);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace gui
}; // namespace wosh
